﻿//-----------------------------------------------------------------------
// <copyright file="CameraCaptureUI.cs" company="In The Hand Ltd">
//     Copyright © 2014 In The Hand Ltd. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Storage;

namespace InTheHand.Media.Capture
{
    public sealed class CameraCaptureUI
    {
        EventWaitHandle handle;
        StorageFile file;

        public IAsyncOperation<StorageFile> CaptureFileAsync(CameraCaptureUIMode mode)
        {
#if WINDOWS_PHONE

            return Task.Run<StorageFile>(() =>
                {
                    handle = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset);
                    Microsoft.Phone.Tasks.CameraCaptureTask task = new Microsoft.Phone.Tasks.CameraCaptureTask();
                    task.Completed += task_Completed;
                    try
                    {
                        task.Show();

                        handle.WaitOne();

                        return file;
                    }
                    catch
                    {
                        return null;
                    }
                }).AsAsyncOperation<StorageFile>();
#else
            //TODO: implement capture
            return null;
#endif
        }

#if WINDOWS_PHONE
        async void task_Completed(object sender, Microsoft.Phone.Tasks.PhotoResult e)
        {
            Stream s = e.ChosenPhoto;
            StorageFile newFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(DateTimeOffset.Now.ToString("yyyyMMddHHmmss") + ".jpg");
            Stream fs = await newFile.OpenStreamForWriteAsync();
            await s.CopyToAsync(fs);
            s.Dispose();
            fs.Dispose();
            file = newFile;
            handle.Set();
        }
#endif
    }
}
